<template>
  <div>
    <el-form :inline="true">
      <el-form-item v-if="hasAuth('role:list')">按信息搜索</el-form-item>
      <el-form-item v-if="hasAuth('role:list')">
        <el-input :placeholder="searchType"
                  v-model="search"
                  class="input-with-select"
                  @change="changeSearchInput"
                  :clearable=true>
          <el-select v-model="searchType" slot="prepend" placeholder="请选择">
            <el-option label="角色名称" value="role_name"></el-option>
            <el-option label="角色描述" value="role_desc"></el-option>
          </el-select>
          <el-button slot="append" icon="el-icon-search" @click="searchData"></el-button>
        </el-input>
      </el-form-item>

      <el-form-item v-if="hasAuth('role:add')">
        <el-button type="primary" @click="editRole(null)">新增角色</el-button>
      </el-form-item>
    </el-form>

    <el-table
        v-if="hasAuth('user:roles')" :data="roleList"
        ref="roleList" border style="width: 100%">
      <el-table-column
          prop="roleId"
          label="角色id"
          width="80">
      </el-table-column>
      <el-table-column
          prop="roleName"
          label="角色名称"
          width="180">
      </el-table-column>
      <el-table-column
          prop="roleDesc"
          label="角色描述"
          width="200">
      </el-table-column>
      <el-table-column
          prop="createTime"
          label="创建时间"
          width="180">
      </el-table-column>
      <el-table-column
          prop="updateTime"
          label="修改时间"
          width="300"
          show-overflow-tooltip>
      </el-table-column>
      <af-table-column
          fixed="right"
          label="操作">
        <template slot-scope="scope">
          <el-button @click="editRole(scope.row)" type="text" size="small"  v-if="hasAuth('role:update')">编辑</el-button>
          <el-button @click="grantPer(scope.row)" type="text" size="small" v-if="hasAuth('role:grant')">分配权限</el-button>
          <el-button @click="deleteRole(scope.row.id)" type="text" size="small" v-if="hasAuth('role:delete')">删除</el-button>
        </template>
      </af-table-column>
    </el-table>
    <!--编辑 新增 角色-->
    <el-dialog
        title="订单操作"
        :visible.sync="editRoleShow"
        :close-on-click-modal="false"
        width="45%"
        center
        :before-close="editRoleClose">

      <el-form ref="roleForm" :rules="roleRules" :model="role" label-width="auto">
        <el-row>
          <el-col :span="12">
            <el-form-item label="角色名称" prop="roleName">
              <el-input v-model="role.roleName"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="角色描述" prop="roleDesc">
              <el-input v-model="role.roleDesc"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>

      <span slot="footer" class="dialog-footer">
        <el-button @click="editRoleClose">取 消</el-button>
        <el-button type="primary" @click="okEditRole">确 定</el-button>
      </span>
    </el-dialog>
    <!--权限-->
    <el-dialog
        title="权限配置"
        :visible.sync="editPermissionShow"
        width="40%"
        :close-on-click-modal="false"
        :before-close="editPermissionCardClose">
      <el-tree
          :data="permissionList" :show-checkbox="true" node-key="id" ref="permissionTree"
          :check-strictly="true" :props="permissionProps">
      </el-tree>

      <span slot="footer" class="dialog-footer">
        <el-button @click="editPermissionCardClose">取 消</el-button>
        <el-button type="primary" @click="okEditPermission">确 定</el-button>
      </span>
    </el-dialog>

    <admin-footer/>
  </div>
</template>

<script>
import {addRole, deleteRoleById, getAllRole, grantRolePermissionByRoleId, updateRole} from "@/network/role";
import {getAllPermissionSimple} from "@/network/permission";
import AdminFooter from "@/components/conment/adminfooter/AdminFooter";
import {hasPermission} from "@/utils/mixin";

export default {
  name: "Role",
  components: {AdminFooter},
  mixins:[hasPermission],
  data(){
    return{
      roleList:[],//所有角色
      roleId:0,
      permissionList:[],//所有权限
      permissionProps:{
        children: 'childList',
        label: 'resourceName'
      },//权限结构
      rolePermission:[],//角色权限
      role:{},//角色
      tempRole:{},//

      editOrAddFlag:false,
      roleRules:{
        roleName:[
          { required: true, message: '请输入角色名称', trigger: 'blur' },
          { min: 3, max: 8, message: '长度在 3 到 8 个字符', trigger: 'blur' },
          { pattern: /[a-zA-Z]/, message: '请输入英文字母' }
        ],
        roleDesc:[
          { required: true, message: '请输入角色描述', trigger: 'blur' },
          { min: 3, max: 10, message: '长度在 3 到 10 个字符', trigger: 'blur' },
        ]
      },
      searchType:'role_name',
      search:'',

      editRoleShow:false,
      editPermissionShow:false,
    }
  },
  methods:{
    //打开编辑 新增角色界面
    editRole(row){
      if (row){//编辑
        this.editOrAddFlag = false
        this.role = JSON.parse(JSON.stringify(row))
        this.tempRole = JSON.parse(JSON.stringify(row))
      }else {//新增
        this.editOrAddFlag = true
        this.role = {}
        this.tempRole = {}
      }
      this.editRoleShow = true
    },
    //打开权限配置界面
    grantPer(row){
      this.editPermissionShow = true
      this.roleId = row.id
      let s = (row.permissionIds?row.permissionIds.split('|'):['0']).map(res=>parseInt(res))
      this.rolePermission = s
      this.$nextTick(() => {//这里会报错 必须用$nextTick？？？
        this.$refs.permissionTree.setCheckedKeys(s,false)
      })
    },
    //关闭编辑角色界面
    editRoleClose(){
      this.$refs.roleForm.clearValidate()
      this.role = {}
      this.tempRole = {}
      this.editRoleShow = false
    },
    //关闭权限修改界面
    editPermissionCardClose(){
      this.editPermissionShow = false
      this.rolePermission = []
    },
    //确认修改权限
    okEditPermission(){
      let checked = this.$refs.permissionTree.getCheckedKeys(false)
      if (JSON.stringify(checked)!==JSON.stringify(this.rolePermission)){
        grantRolePermissionByRoleId(checked,this.roleId).then(res=>{
          this.$message.success('修改成功')
          this.getRoleInfo(this.current,this.size,'','')
        })
      }
      this.editPermissionShow = false
    },
    //确认修改 新增角色
    okEditRole(){
      this.$refs.roleForm.validate(valid=>{
        if (valid){
          if(this.editOrAddFlag){//添加
            addRole(this.role).then(res=>{
              if (res.data.code===200){
                this.getRoleInfo('','')
                this.$message.success('添加成功')
              }else {
                this.$message.error('添加失败')
              }
            })
          }else {//编辑
            if (JSON.stringify(this.role) !== JSON.stringify(this.tempRole)){
              updateRole(this.role).then(res=>{
                if (res.data.code === 200) {
                  this.getRoleInfo('','')
                  this.$message.success('修改成功')
                } else {
                  this.$message.error('修改失败')
                }
              })
            }
          }
          this.editRoleClose()
        }else {
          console.log('表单验证失败')
        }
      })
    },
    deleteRole(id){
      this.$confirm('删除此角色?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        deleteRoleById(id).then(res=>{
          this.$message.success('删除成功')
          this.getRoleInfo(this.current,this.size,'','')
        })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '取消删除'
        });
      });

    },
    changeSearchInput(){
      if (this.search===''){
        this.getRoleInfo('','')
      }
    },
    searchData(){
      if (this.search!==''){//数据不为空
        this.getRoleInfo(this.searchType,this.search)
      }else {
        this.$message.warning("请输入数据后再查询")
      }
    },
    //获取所有角色信息
    getRoleInfo(type,data){
      getAllRole(type,data).then(res=>{
        if (res.data.data.length===0)
          this.$message.info("未找到符合条件的数据")
        else {
          this.roleList = res.data.data
        }
      })
    }
  },
  mounted() {
    this.getRoleInfo('','')
    getAllPermissionSimple().then(res=>{
      this.permissionList = res.data.data
    })
  }
}
</script>
<style scoped>
</style>